import { openDB } from "idb";

const dbName = "myDatabase";
const dbVersion = 1;
let dbPromise;

export const openDatabase = () => {
  if (!dbPromise) {
    dbPromise = openDB(dbName, dbVersion, {
      upgrade(db) {
        // 如果需要创建新的对象存储空间，可以在这里添加
        if (!db.objectStoreNames.contains("myStore")) {
          db.createObjectStore("myStore", { keyPath: "id" });
        }
      },
    });
  }
  return dbPromise;
};

export const addData = async (data) => {
  const db = await openDatabase();
  const tx = db.transaction("myStore", "readwrite");
  const store = tx.objectStore("myStore");
  await store.put(data);
  await tx.done;
};

export const getData = async (id) => {
  const db = await openDatabase();
  const tx = db.transaction("myStore", "readonly");
  const store = tx.objectStore("myStore");
  return store.get(id);
};

export const removeData = async (id) => {
  const db = await openDatabase();
  const tx = db.transaction("myStore", "readwrite");
  const store = tx.objectStore("myStore");
  await store.delete(id);
  await tx.done;
};
